var db = require('../dbutil/index');
var sql = require('../dbutil/sql');
var token = require('../util/token');

module.exports = {
    login: (req, res) => {
        let uname = req.body.uname;   //请求体获取
        let upass = req.body.upass;
        db.query(sql.users.login, [uname, upass], (err, results) => {
            if (err) {
                res.send({ code: 500, message: 'sql执行错误' });
            } else {
                if (results.length > 0) {  //调用token.setToken()方法生成一个token
                    token.setToken(results[0].uname, results[0].uid).then((data) => { //返回的data就是生成的token信息
                        console.log(data)
                        res.send({
                            code: 200,
                            message: '登录成功',
                            data: {
                                token: data,
                                user: results[0]
                            }
                        })
                    });
                } else {
                    res.send({ code: 201, message: '用户名或密码错误' });
                }
            }
        })
    },
    login2: (req, res) => {
        const { adname, adword } = req.body;  //请求体获取
        db.query(sql.users.login2, [adname, adword], (err, results) => {
            if (err) {
                res.send({ code: 500, message: 'sql执行错误' });
            } else {
                if (results.length > 0) { //匹配到管理员账户
                    let adminName = results[0].adname; // 获取查询结果中第一个匹配的管理员用户名  
                        res.send({
                            code: 200,
                            message: '登录成功',
                            adminName: adminName // 将管理员用户名添加到响应数据中
                    });
                } else {
                    res.send({ code: 201, message: '管理员账号或密码错误,请重新输入!' });
                }
            }
        })
    },
    reg: (req, res) => { //请求体获取
        let uname = req.body.uname;
        let upass = req.body.upass;
        let nickname = req.body.nickname;
        db.query(sql.users.userByname, [uname], (err1, results1) => { //userByname根据用户名查用户是否存在
            if (err1) {
                res.send({ code: 500, message: 'sql执行错误' });
            } else {
                if (results1.length > 0) { //找到数据，不允许注册
                    res.send({ code: 201, message: '用户名已存在,不能注册' });
                } else {
                    db.query(sql.users.reg, [uname, upass, nickname], (err2, results2) => {
                        if (err2) {
                            res.send({ code: 500, message: 'sql执行错误' });
                        }else{
                            res.send({ code: 200, message: '注册成功' });
                        }
                    })
                }

            }
        })



    }
}